package cn.sc.summer.warm.service;

import cn.sc.summer.constant.project.ProjectConstant;
import cn.sc.summer.constant.warmup.WarmUpConstant;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.warm.endpoint.WarmupEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;

/**
 * 类名：预热接口配置项
 *
 * @author a-xin
 * @date 2024/7/1 15:06
 */
@Slf4j
@Service
public class WarmUpService implements DisposableBean {

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 注册预热接口信息
     *
     * @throws NoSuchMethodException 预热接口指定方法未找到异常
     */
    public void register() throws NoSuchMethodException {
        RequestMappingHandlerMapping mapping = applicationContext.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
        RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(WarmUpConstant.WARM_UP).methods(RequestMethod.GET).build();
        mapping.registerMapping(requestMappingInfo, "warmupEndpoint", WarmupEndpoint.class.getDeclaredMethod("warmup"));
        RedisHelper.del(WarmupEndpoint.WARM_UP + ProjectConstant.SERVER_NAME);
        log.info("==> The warm up interface: {} has been registered!", WarmUpConstant.WARM_UP);
    }

    /**
     * 注销预热接口信息
     */
    public void unRegister() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
        RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(WarmUpConstant.WARM_UP).methods(RequestMethod.GET).build();
        mapping.unregisterMapping(requestMappingInfo);
        RedisHelper.del(WarmupEndpoint.WARM_UP + ProjectConstant.SERVER_NAME);
        log.warn("==> The warm up interface: {} has been unRegistered!", WarmUpConstant.WARM_UP);
    }

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     */
    @Override
    public void destroy() {
        this.unRegister();
    }
}
